package correspondence;
/*
三条线程通信
面试问题;
1.sleep方法和wait方法的区别
    sleep方法是线程休眠，时间到了自动醒来，其在休眠的时候不会释放锁
    wait方法线程等待，需要由其他线程进行notify唤醒，其在等待期间，会释放锁
 */
public class Demo2 {
    public static void main(String[] args) {
        Printer2 p = new Printer2();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (Printer2.class) {
                        try {
                            p.print1();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (Printer2.class) {
                        try {
                            p.print2();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();
        new Thread(() -> {

            while (true) {
                synchronized (Printer2.class) {
                    try {
                        p.print3();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
}
class Printer2{
    int flag = 1;
    public void print1() throws InterruptedException {
        while (flag != 1) {
            Printer2.class.wait();
        }
        System.out.print("周");
        System.out.print("新");
        System.out.print("琦");
        System.out.println();
        flag = 2;
        //唤醒所有线程
        Printer2.class.notifyAll();
    }
    public void print2() throws InterruptedException {
        while (flag != 2) {
            Printer2.class.wait();
        }
        System.out.print("麦");
        System.out.print("啊");
        System.out.print("迷");
        System.out.println();
        flag = 3;
        Printer2.class.notifyAll();
    }
    public void print3() throws InterruptedException {
        while (flag != 3) {
            Printer2.class.wait();
        }
        System.out.print("c");
        System.out.print("s");
        System.out.print("go");
        System.out.println();
        flag = 1;
        Printer2.class.notifyAll();
    }

}
